package com.xiaoming.plugin.tcp.utils;

import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HexUtil {

    public static String byte2hex(byte[] b) {
        // String Buffer can be used instead
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
            if (n < b.length - 1) {
                hs = hs + "";
            }
        }
        return hs;
    }

    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            bytes[i / 2] =
                    (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    public static String readInputStream(BufferedInputStream _in) throws IOException {
        String data = "";
        int s = _in.read();
        if (s == -1)
            return null;
        data += "" + (char) s;
        int len = _in.available();
        // System.out.println("Len got : " + len);
        if (len > 0) {
            byte[] byteData = new byte[len];
            _in.read(byteData);
            data += new String(byteData);
            if (true) {
                data = "";
                byte[] bb = new byte[1];
                bb[0] = (byte) s;
                data += byte2hex(bb);
                data += byte2hex(byteData);
            }
        }
        return data;
    }

    public static String readInputStream(DataInputStream _in) throws IOException {
        String data = "";
        int s = _in.read();
        if (s == -1)
            return null;
        data += "" + (char) s;
        int len = _in.available();
        // System.out.println("Len got : " + len);
        if (len > 0) {
            byte[] byteData = new byte[len];
            _in.read(byteData);
            data += new String(byteData);
            if (true) {
                data = "";
                byte[] bb = new byte[1];
                bb[0] = (byte) s;
                data += byte2hex(bb);
                data += byte2hex(byteData);
            }
        }
        return data;
    }

    //char to int
    static int char2Int(char str) {
        switch (str) {
            case '0':
                return 0;
            case '1':
                return '1';
            case '2':
                return 2;
            case '3':
                return 3;
            case '4':
                return 4;
            case '5':
                return 5;
            case '6':
                return 6;
            case '7':
                return 7;
            case '8':
                return 8;
            case '9':
                return 9;
            case 'a':
            case 'A':
                return 10;
            case 'b':
            case 'B':
                return 11;
            case 'c':
            case 'C':
                return 12;
            case 'd':
            case 'D':
                return 13;
            case 'e':
            case 'E':
                return 14;
            case 'f':
            case 'F':
                return 15;

        }
        return 0;
    }

    //hex to int
    //2位
    public static int hex2Int(String str) {
        char[] c1 = str.toCharArray();
        return char2Int(c1[0]) * 16 + char2Int(c1[1]);
    }

    //粘包处理
    public static List<String> glue(String sourceStr) {
        List<String> res = new ArrayList<>();

        if (!TextUtils.isEmpty(Params.regex)) {
            //优先处理第二个指令，避免影响第一个指令
            Pattern pattern = Pattern.compile(Params.regex);
            Matcher matcher = pattern.matcher(sourceStr);

            while (matcher.find()) {
                String result = matcher.group();
                res.add(result);
//            System.out.println(result);
                sourceStr = sourceStr.replaceFirst(result, "");
            }
        }

        String[] msgArray = sourceStr.split("(?=" + Params.hexHead + ")");
        String lastPart = "";
        for (int i = 0; i < msgArray.length; i++) {
            String msg = msgArray[i];

            //头正常
            if (msg.startsWith(Params.hexHead)) {
                try {
                    if (Params.hexDataLengthIndex + 2 > msg.length()) {
                        lastPart = msg;
                        break;
                    }
                    //计算长度
                    String dataLength = msg.substring(Params.hexDataLengthIndex, Params.hexDataLengthIndex + 2);
                    int msglength = hex2Int(dataLength) * 2 + Params.hexHead.length() + 2 + Params.hexDataOtherLength;
                    if (msg.length() == msglength) {
                        res.add(msg);
                    } else if (msg.length() < msglength) {
                        if (i == msgArray.length - 1) {
                            lastPart = msg;
                        } else {
                            res.add(msg);
                        }
                    } else if (msg.length() > msglength) {
                        lastPart = msg.substring(msglength);
                        msg = msg.substring(0, msglength);
                        res.add(msg);
                    }
                } catch (Exception ex) {
//                    throw ex;
                }
            } else if (msg.length() < Params.hexHead.length()) {
                lastPart = msg;
            }
            //如果总数据的头都不对，丢掉
        }
        res.add(lastPart);
        return res;
    }
}
